#include "IPC_Sem.h"


int IPC_SemInit(int semid, int initsems)
{
    int sid = -1;
    sid = semget(semid, 0, 0666);
    if (sid < 0)
    {
        sid = semget(semid, initsems, IPC_CREAT| IPC_EXCL | 0666);
        if (sid < 0)
        {
            COMLOG_ERROR_LOG("semget: %d\n", sid);
            return -1;
        }
    }
    return sid;
}



int IPC_SemDeinit(int semid)
{
   return semctl(semid, 0, IPC_RMID);

}



int IPC_SemLock(int semid, int subval)
{
    struct sembuf buf;
    buf.sem_num = 0;//信号量下标
    buf.sem_op = -subval;//p操作
    buf.sem_flg = SEM_UNDO;
    if(semop(semid,&buf,1)==-1)
    {
        COMLOG_ERROR_LOG("semop error\n");
        return -1;
    }
    return 0;
}


int IPC_SemunLock(int semid, int addval)
{
    struct sembuf buf;
    buf.sem_num = 0;//信号量下标
    buf.sem_op = addval;//p操作
    buf.sem_flg = SEM_UNDO;
    if(semop(semid,&buf,1)==-1)
    {
        COMLOG_ERROR_LOG("semop error\n");
        return -1;
    }
    return 0;


}